package net.zwet.clanworks.common;

/**
 * Created with IntelliJ IDEA.
 * User: Hansz
 * Date: 6/12/13
 * Time: 5:31 PM
 * To change this template use File | Settings | File Templates.
 */
import java.security.SignatureException;
import java.util.Arrays;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.Encoder;
import org.apache.commons.codec.binary.Base64;

/**
 * This class defines common routines for generating
 * authentication signatures for AWS requests.
 */
public class Signature {
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

    /**
     * Computes RFC 2104-compliant HMAC signature.
     * @param data The data to be signed.
     * @param privateKey The signing key.
     * @return The Base64-encoded RFC 2104-compliant HMAC signature.
     * @throws
     *      java.security.SignatureException when signature generation fails
     */
    public static String calculateHMAC(String data, String privateKey)
            throws java.security.SignatureException
    {
        byte[] result;
        try {
            // get an hmac_sha1 key from the raw key bytes
            SecretKeySpec signingKey = new SecretKeySpec(privateKey.getBytes(), HMAC_SHA1_ALGORITHM);

            // get an hmac_sha1 Mac instance and initialize with the signing key
            Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            mac.init(signingKey);

            // compute the hmac on input data bytes
            byte[] rawHmac = mac.doFinal(data.getBytes());

            // base64-encode the hmac
            result = Base64.encodeBase64(rawHmac);
            return Arrays.toString(result);
        } catch (Exception e) {
            throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
        }
    }
}
